<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Services\OSS;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class CouponOrder extends Model
{
    protected $dateFormat = 'U';
    //
    protected $table = "lexiang_coupon_order";

    public function add($data)
    {
    	$this->order_number = $this->createOrderNumber();
    	$this->total = $data['total'];
    	$this->user_id = $data['user_id'];
    	$this->openid = $data['openid'];
    	$this->pay_state = 0;
    	$this->coupon_id = $data['coupon_id'];
    	$this->dopay_at = 0;
    	$this->qrcode = $this->createQrCode($this->order_number);

    	if($this->save()){
    		return ['success'=>true,'code'=>"000",'message'=>'订单提交成功，请尽快支付','data'=>[
    			'order_number'=>$this->order_number,
    			'total'=>$this->total,
    			'openid'=>$this->openid,
    		]];
    	}else{
    		return ['success'=>false,'code'=>'006','message'=>'添加出错，请稍后再试！'];
    	}
    }

    /**
     * 生成二维码
     */
    public function createQrCode($orderNum)
    {
    	$pathdir = base_path()."/resources/tmp/".$orderNum.'.png';
    	QrCode::encoding('UTF-8')->format('png')->size(800)->margin(1)->generate('https://console.jiashilexiang.cn/api/coupon/kill?no='.$orderNum,$pathdir);
    	$fileName = 'CouponQrcode/'.date('Ymd').'/'.$orderNum.'.png';
        $upRes = OSS::publicUpload(config('aliyun.BucketName'),$fileName,$pathdir);
        unlink($pathdir);
        return $fileName;
    }

    private function createOrderNumber()
    {
    	return time().rand(11111,99999);
    }

    /**
     * 核销打款到商户
     */
    public function useToShop()
    {

    }

    /**
     * 处理二维码
     */
    public function getQrcodeAttribute($v)
    {
    	return "https://jiashilexiang.oss-cn-beijing.aliyuncs.com/".$v;
    }

    public function getNicknameAttribute($v)
    {
    	return User::where('user_id',$this->user_id)->value('nicename');
    }

    public function getPayStateTextAttribute($v)
    {
    	$de = ['未支付','已支付'];
    	return $de[$this->pay_state];
    }

    public function getStartTimeAttribute($v)
    {
    	return date("Y-m-d",$v);
    }

    public function getOverTimeAttribute($v)
    {
    	return date('Y-m-d',$v);
    }

    public function getCreatedAtAttribute($v)
    {
    	return date("Y-m-d H:i",$v);
    }

    public function getUpdatedAtAttribute($v)
    {
    	return date('Y-m-d H:i',$v);
    }

    public function getUseAtAttribute($v)
    {
        return date('Y-m-d',$v);
    }
}
